package com.dge.common.proxy

import com.dge.common.base.presenter.BasePresenter
import com.dge.common.base.view.MvpView
import com.dge.common.interfaces.InjectPresenter
import java.lang.reflect.Field

/**
 * <pre>
 *     author : dge
 *     e-mail : 229605030@qq.com
 *     time   : 2021/01/30
 *     desc   :
 * </pre>
 */
open class MvpProxyImpl(val view: MvpView) : IMvpProxy {
    private var mInjectPresenters: MutableList<BasePresenter<*, *>>? = null

    init {
        mInjectPresenters = ArrayList()
    }

    override fun bindPresenter() {
        //获得已经申明的变量，包括私有的
        val fields: Array<Field> = view.javaClass.declaredFields
        for (field in fields) {
            //获取变量上面的注解类型
            val injectPresenter = field.getAnnotation(InjectPresenter::class.java)
            if (injectPresenter != null) {
                try {
                    val type = field.type as Class<out BasePresenter<*, *>>
                    val mInjectPresenter = type.newInstance()
                    mInjectPresenter.attachView(view)
                    field.isAccessible = true
                    field.set(view, mInjectPresenter)
                    mInjectPresenters!!.add(mInjectPresenter)
                } catch (e: IllegalAccessException) {
                    e.printStackTrace()
                } catch (e: InstantiationException) {
                    e.printStackTrace()
                } catch (e: ClassCastException) {
                    e.printStackTrace()
                    throw RuntimeException("SubClass must extends Class:BasePresenter")
                }
            }
        }
    }

    override fun unbindPresenter() {
        /**
         * 解绑，避免内存泄漏
         */
        for (presenter in mInjectPresenters!!) {
            presenter.detachView()
        }
        mInjectPresenters!!.clear()
        mInjectPresenters = null
    }
}